package com.andova.util;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import androidx.core.content.FileProvider;

/**
 * Created by Administrator on 2017-03-28.
 */
public class GASystemCamera {
    private static String mCurrentPhotoPath;

    public static String getCurrentPhotoPath() {
        return mCurrentPhotoPath;
    }

    public static void takeCamera(Activity startActivity, int requestCode) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takePictureIntent.putExtra("autofocus", true); // 自动对焦
        takePictureIntent.putExtra("fullScreen", true); // 全屏
        takePictureIntent.putExtra("showActionIcons", false);

        File photoFile = null;
        try {
            photoFile = createImageFile(startActivity);
        } catch (IOException ex) {
            // Error occurred while creating the File
            // alchen todo ...
        }

        // Continue only if the File was successfully created
        if (photoFile != null) {
            String authority = "com.andova.fileprovider." + startActivity.getPackageName();
            Uri photoURI = Build.VERSION.SDK_INT < Build.VERSION_CODES.N ? Uri.fromFile(photoFile)
                    : FileProvider.getUriForFile(startActivity, authority, photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

//            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCurrentPhotoPath);

            if (takePictureIntent.resolveActivity(startActivity.getPackageManager()) != null) {
                startActivity.startActivityForResult(takePictureIntent, requestCode);
            }
        }
    }

    private static File createImageFile(Activity startActivity) throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = startActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }
}
